/**
 * 文件名称:  DictServiceImpl.java
 * 文件序号:  序号
 * 内容描述:  文件简单描述，多行换行书写
 * 版权声明:  山东鸿蝶信息技术有限公司
 * 创建用户:  zhangkai
 * 创建日期:  2017/1/16 08:24
 * 修改用户:  无
 * 修改日期:  无
 * 修改说明:  无
 * 文件版本:  V1.0
 * 文件路径:
 */

package com.hongdee.base.dict.service.impl;


import com.hongdee.base.Constant;
import com.hongdee.base.dict.dao.IDictDao;
import com.hongdee.base.dict.entity.TBcNewDict;
import com.hongdee.base.dict.service.IDictService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.view.tiles3.SpringBeanPreparerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hongdee.base.Constant.P_ROOT_ID;

/**
 * 名  称:DictServiceImpl
 * 类  型: class
 * 描  述: 用一句话描述类的作用
 * 路  径:com.hongdee.base.dict.service.impl
 * 作  者:zhangkai
 * 日  期:2017/1/16 08:24
 */
@Service
public class DictServiceImpl implements IDictService {
    private String NEW_DICT_TABLE = "T_BC_NEWDICT";

    @Autowired
    private IDictDao dictDao;

    //字典下拉列表
    private static Map dictComboMap = null;

    //字典转换列表
    private static Map dictConvertMap = null;


    /**
     * 方法名称: info
     * 方法描述: 详情查询
     * 参数名称: String id 品牌id
     * 返回内容: 实体对象
     * 异常说明: Exception
     * 创建用户:张国凯
     * 创建时间:
     * 修改用户:术洪超
     * 修改时间:2017/2/8
     * 修改内容:注释内容
     */
    @Override
    public Map info(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择字典记录");
        }
        String sql = "select * from " + NEW_DICT_TABLE + " where id = ? ";
        return this.dictDao.info(sql, new Object[]{id});
    }

    /**
     * 方法名称: update
     * 方法描述: 修改品牌状态
     * 参数名称: String id  品牌id
     * 参数名称: String status 品牌状态
     * 返回内容:
     * 异常说明:Exception
     * 创建用户:张国凯
     * 创建时间:
     * 修改用户:术洪超
     * 修改时间:2017/2/8
     * 修改内容:注释内容
     */
    @Override
    public void update(String id, String status) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择字典记录");
        }
        String hql = "update TBcNewDict set status = :status where id = :id ";
        Map params = new HashMap();
        params.put("id", id);
        params.put("status", status);
        this.dictDao.update(hql, params);
    }

    /**
     * 方法名称: saveOrUpdate
     * 方法描述:  保存或更新实体，通过主键判断
     * 参数名称: TBcDict dict 要保存的变更历史记录实体
     * 返回内容: TBcDict 保存后的历史记录实体
     * 异常说明: Exception
     * 创建用户:张国凯
     * 创建时间:
     * 修改用户:术洪超
     * 修改时间:2017/2/8
     * 修改内容:注释内容
     */
    @Override
    public TBcNewDict saveOrUpdate(TBcNewDict dict) throws Exception {
        //根据字典分组、字典存储值去重
        if (null == dict.getId() || StringUtils.isEmpty(dict.getId())) {
            //新增时判断是否已经存在
            if (isExist(dict.getLabel(), dict.getCode(), dict.getpCode(), null, dict.getType(), Constant.ADD)) {
                throw new Exception("该分组下已存在相同的字典标签或字典值！");
            }
            this.dictDao.saveOrUpdate(dict);
        } else {
            if (isExist(dict.getLabel(), dict.getCode(), dict.getpCode(), dict.getId(), dict.getType(), Constant.UPDATE)) {
                throw new Exception("该分组下已存在相同的字典标签或字典值！");
            }
            Map oldMap = this.dictDao.info(NEW_DICT_TABLE, "id", dict.getId());
            this.dictDao.saveOrUpdate(dict);
            //更新父节点
            this.dictDao.update("update TBcNewDict set pCode='" + dict.getCode() + "' where pCode='" + oldMap.get("code") + "'", new HashMap<>());
        }

        initDictMap();
        //修正下一级编码
        return dict;
    }

    /**
     * 方法名称: combo
     * 方法描述:品牌下拉列表
     * 参数名称：String group 字典分组
     * 返回内容: List
     * 异常说明: Exception
     * 创建用户:张国凯
     * 创建时间:
     * 修改用户:术洪超
     * 修改时间:2017/2/8
     * 修改内容:注释内容
     */
    @Override
    public List<Map> combo(String group) throws Exception {
        /****
         * 增加状态过滤
         *
         * */
        if (dictComboMap == null) {
            initDictMap();
        }
        if (dictComboMap.containsKey(group)) {
            return (List<Map>) dictComboMap.get(group);
        }
        String sql = " select * from " + NEW_DICT_TABLE + " where  status='1' and   p_code = ?  ";
        List<Map<String, Object>> mapList = this.dictDao.list(sql, group);
        List<Map> resList = new ArrayList<Map>();
        Map temp;
        for (Map map : mapList) {
            temp = new HashMap();
            temp.put("label", map.get("label"));
            temp.put("value", map.get("code"));
            temp.put("group", map.get("pCode"));
            temp.put("id", map.get("id"));
            resList.add(temp);
        }
        return resList;
    }

    /**
     * 根据编码查询公共字典
     *
     * @param group
     * @return
     * @throws Exception
     */
    @Override
    public List<Map> comboInsurance(String group) throws Exception {
        String sql = " select * from " + NEW_DICT_TABLE + " where  status='1' and   p_code = ?  ";
        List<Map<String, Object>> mapList = this.dictDao.list(sql, group);
        List<Map> resList = new ArrayList<Map>();
        Map temp;
        for (Map map : mapList) {
            temp = new HashMap();
            temp.put("label", map.get("label"));
            temp.put("value", map.get("code"));
            temp.put("group", map.get("pCode"));
            temp.put("id", map.get("id"));
            resList.add(temp);
        }
        return resList;
    }

    /**
     * 方法名称:convert
     * 方法描述:品牌编码转换
     * 参数名称：String group 字典分组
     * 返回内容:
     * 异常说明: Exception
     * 创建用户:张国凯
     * 创建时间:
     * 修改用户:术洪超
     * 修改时间:2017/2/8
     * 修改内容:注释内容
     */
    @Override
    public Map<String, String> convert(String group) throws Exception {
        if (dictConvertMap == null) {
            initDictMap();
        }
        if (dictConvertMap.containsKey(group)) {
            return (Map<String, String>) dictConvertMap.get(group);
        }

        String sql = " select * from " + NEW_DICT_TABLE + " where  p_code = ?  ";
        List<Map<String, Object>> mapList = this.dictDao.list(sql, group);
        List<Map> resList = new ArrayList<Map>();
        Map temp = new HashMap();
        for (Map map : mapList) {
            temp.put(map.get("code"), map.get("label"));
        }
        return temp;
    }


    /**
     * 方法名称:isExist
     * 方法描述:判断字典值是否重复
     * 参数名称：String group 字典分组
     * 参数名称：String value 字典存储值
     * 参数名称：String id 业务主键
     * 参数名称：int type 字典类型
     * 返回内容: boolean
     * 异常说明: Exception
     * 创建用户:张国凯
     * 创建时间:
     * 修改用户:术洪超
     * 修改时间:2017/2/8
     * 修改内容:注释内容
     */


//判断字典值是否重复
    private boolean isExist(String label, String code, String pcode, String id, String dictType, int type) throws Exception {
        String sql = "select * from " + NEW_DICT_TABLE + " where  label= ? and code = ?  ";
        List param = new ArrayList();
        param.add(label);
        param.add(code);
        //分组的编码不能重复，字典值关联分组后不能重复
        if (dictType.equals("0")) {
            //分组
        } else {
            sql += " and p_code = ? ";
            param.add(pcode);
        }


        if (Constant.UPDATE == type) {
            sql += " and  id != ? ";
            param.add(id);
        }
        Map map = this.dictDao.page(sql, param.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;
    }

    /**
     * 分组分页
     */
    @Override
    public Map page(String start, String limit, String searchValue) throws Exception {
        String sql = "SELECT * FROM " + NEW_DICT_TABLE + " WHERE type = '0' and (code like ? or lable like ? or remark like ?) ";
        String sV = "%" + searchValue + "%";
        Object[] params = new Object[]{sV, sV, sV};
        return this.dictDao.page(sql, params, start, limit);
    }

    /**
     * 分组详情
     */
    @Override
    public Map groupInfo(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择字典分组记录");
        }
        String sql = "SELECT * FROM " + NEW_DICT_TABLE + " where type= '0'and id = ? ";
        return this.dictDao.info(sql, new Object[]{id});
    }

    /**
     * 查询字典树
     *
     * @param pCode 上级节点编码
     * @return
     */
    @Override
    public List tree(String pCode) throws Exception {

        String rootId = P_ROOT_ID;
        if (!"".equals(pCode)) {
            rootId = pCode;
        }
        return buildDictChild(rootId, false);
    }

    /***
     * 查询
     * @param pCode 默认为分组类型
     * @return
     */
    @Override
    public List treeDict(String pCode) throws Exception {
        return buildDictChild(pCode, false);
    }

    private List buildDictChild(String key, boolean hasDict) throws Exception {
        //从缓存中取得用户已有的角色

        String sqlStr = " select * from T_BC_NEWDICT where p_code = ? ";
        if (!hasDict) {
            sqlStr += " and type = '0' ";
        }
        List<Map<String, Object>> treeP = this.dictDao.list(sqlStr, key);
        return buildDictParent(treeP, hasDict);
    }

    private List buildDictParent(List<Map<String, Object>> dictList, boolean hasDict) throws Exception {
        if (dictList.size() == 0) {
            return dictList;
        }
        List<Map<String, Object>> childList;
        for (Map map : dictList) {
            String code = String.valueOf(map.get("code"));
            childList = buildDictChild(code, hasDict);
            //存在子节点，增加子节点 返回
            map.put("child", childList);
        }
        return dictList;
    }

    /**
     * 新字典分頁
     */
    @Override

    public Map newPage(String start, String limit, String pCode, String value, String status) throws Exception {
        String sql = "select * from " + NEW_DICT_TABLE + " where p_code = ?   ";
        List<Object> params = new ArrayList();
        params.add(pCode);
        if (!StringUtils.isEmpty(value)) {
            sql += " and ( code  like  ? or label like ? ) ";
            params.add("%" + value + "%");
            params.add("%" + value + "%");
        }
        if (!"".equals(status)) {
            sql += " and status = ? ";
            params.add(status);
        }
        sql += " order by status desc";
        System.out.println(sql);
        return this.dictDao.page(sql, params.toArray(), start, limit);
    }

    /**
     * 查询所有短信模板
     */
    @Override
    public List msgModle(String code) throws Exception {
        List<Map> resList = new ArrayList<Map>();
        String sql = "select label,code from " + NEW_DICT_TABLE + " where p_code = 'msgModle' and code = ? ";
        List<Map<String, Object>> mapList = this.dictDao.list(sql, code);
        Map temp;
        for (Map map : mapList) {
            temp = new HashMap();
            temp.put("value", map.get("code"));
            temp.put("label", map.get("label"));
            resList.add(temp);
        }
        return resList;
    }


    /**
     * 查询多个字典分组
     *
     * @param groups
     * @return
     */
    @Override
    public Map<String, List<Map>> comboGroup(String groups) throws Exception {
        if (dictComboMap == null) {
            initDictMap();
        }
        Map tempMap = new HashMap<>();
        String group[] = groups.split(",");
        for (String temp : group) {
            if (dictComboMap.containsKey(temp)) {
                tempMap.put(temp, dictComboMap.get(temp));
            } else {
                tempMap.put(temp, new ArrayList<>());
            }
        }
        return tempMap;
    }

    /***
     * 初始化字典
     * **/
    private void initDictMap() throws Exception {
        dictComboMap = new HashMap();
        dictConvertMap = new HashMap();

        //获取分组
        String dictGroupSQL = "select code,label from t_bc_newdict where type = 0 and status = 1 ";
        List<Map<String, Object>> groupList = this.dictDao.list(dictGroupSQL);

        String sql = " select * from " + NEW_DICT_TABLE + " where  status='1' and   p_code = ? ";
        for (Map<String, Object> mp : groupList) {
            String group = String.valueOf(mp.get("code"));
            List<Map<String, Object>> itemList = this.dictDao.list(sql, group);
            //下拉列表
            List<Map> combo = new ArrayList<Map>();
            Map temp;
            //转换字典
            Map tempConv = new HashMap();
            for (Map map : itemList) {
                temp = new HashMap();
                temp.put("label", map.get("label"));
                temp.put("value", map.get("code"));
                combo.add(temp);

                tempConv.put(map.get("code"), map.get("label"));

            }
            dictComboMap.put(group, combo);
            dictConvertMap.put(group, tempConv);

        }

    }

    /**
     * 查询多个字典分组
     *
     * @param groups
     * @return
     */
    @Override
    public Map<String, Map> convertGroup(String groups) throws Exception {
        if (dictConvertMap == null) {
            initDictMap();
        }
        Map tempMap = new HashMap<>();
        String[] group = groups.split(",");
        for (String temp : group) {
            if (dictConvertMap.containsKey(temp)) {
                tempMap.put(temp, dictConvertMap.get(temp));
            } else {
                tempMap.put(temp, new HashMap<>());
            }
        }
        return tempMap;
    }

}

